package controllers;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.tom.basic.serialize.json.GsonUtils;
import com.tom.basic.service.ServiceQueryResult;
import com.tom.basic.service.ServiceResult;
import controllers.filter.FilterAdminPortal;
import models.*;
import models.services.KeJianService;
import models.services.SubjectDictionaryService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import play.mvc.Controller;
import play.mvc.With;
import support.AnswerDO;
import support.AppBanner;
import support.BigCate;
import support.ImportExcelVo;
import utils.MenuData;
import utils.OssUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@With(FilterAdminPortal.class)
public class AdminPortal extends Controller {

    public static void login(String userName, String password) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            renderJSON(ServiceResult.asFail("账号或者密码错误"));
        }
        AdminUser user =
                AdminUser.find("isDelete = 0 and userName=:userName and password=:password").setParameter("password", password).setParameter("userName", userName).first();
        if (user == null) {
            renderJSON(ServiceResult.asFail("账号或者密码错误"));
        }
        renderJSON(ServiceResult.asSuccess(user).toJson());
    }

    public static void logout() {
        renderJSON(ServiceResult.asSuccess("登出成功"));
    }

    public static void menuData() {
        JSON json = JSONUtil.parse(MenuData.MENU_DATA);
        renderJSON(ServiceResult.asSuccess(json));
    }


    public static void querySubjectDictionary(Long bigCateId) {
        renderJSON(ServiceQueryResult.asSuccess(SubjectDictionaryService.querySubDict(bigCateId)).toJson());
    }

    public static void addSubjectDictionary(Long id, Long bigCateId, String name, Integer sortOrder, String shareImg, Integer vipSub,
                                            BigDecimal fee) {
        if (StringUtils.isEmpty(name)) {
            renderJSON(ServiceResult.asFail("请输入名字"));
        }
        if (StringUtils.isEmpty(name) || sortOrder == null || vipSub == null) {
            renderJSON(ServiceResult.asFail("参数异常"));
        }
        SubjectDictionary subjectDictionary = new SubjectDictionary();
        if (id != null) {
            subjectDictionary = SubjectDictionary.findById(id);
        }
        subjectDictionary.bigCateId = bigCateId;
        subjectDictionary.dictName = name;
        subjectDictionary.shareImg = shareImg;
        subjectDictionary.sortOrder = sortOrder;
        subjectDictionary.save();
        renderJSON(ServiceResult.asSuccess("添加成功"));
    }


    public static void delSubjectDictionary(Long id) {
        if (id == null) {
            renderJSON(ServiceResult.asFail("参数异常"));
        }
        SubjectDictionary subjectDictionary = SubjectDictionary.findById(id);
        if (subjectDictionary != null) {
            subjectDictionary.isDelete = 1;
            subjectDictionary.save();
        }
        renderJSON(ServiceResult.asSuccess("删除成功"));
    }


    public static void queryChildSubjectDictionary(Long subjectId) {
        renderJSON(ServiceQueryResult.asSuccess(ChildSubjectDictionary.find("isDelete = 0 and parentId=:parentId  order by sortOrder " +
                "desc").setParameter("parentId", subjectId).fetch()).toJson(ChildSubjectDictionary.class));
    }


    public static void addChildSubjectDictionary(Long id, Long subjectId, String name, Integer sortOrder, Integer vipSub,
                                                 BigDecimal fee) {
        if (StringUtils.isEmpty(name) || sortOrder == null || subjectId == null) {
            renderJSON(ServiceResult.asFail("参数异常"));
        }
        ChildSubjectDictionary childSubjectDictionary = new ChildSubjectDictionary();
        if (id != null) {
            childSubjectDictionary = ChildSubjectDictionary.findById(id);
        }
        childSubjectDictionary.vipSub = vipSub;
        childSubjectDictionary.fee = fee;
        childSubjectDictionary.parentId = subjectId;
        childSubjectDictionary.dictName = name;
        childSubjectDictionary.sortOrder = sortOrder;
        childSubjectDictionary.save();
        renderJSON(ServiceResult.asSuccess("添加成功"));
    }


    public static void delChildSubjectDictionary(Long id) {
        if (id == null) {
            renderJSON(ServiceResult.asFail("参数异常"));
        }
        ChildSubjectDictionary subjectDictionary = ChildSubjectDictionary.findById(id);
        if (subjectDictionary != null) {
            subjectDictionary.isDelete = 1;
            subjectDictionary.save();
        }
        renderJSON(ServiceResult.asSuccess("删除成功"));
    }


    /**
     * 上传文件
     *
     * @param file
     */
    public static void uploadFile(File file) {
        if (file == null) {
            renderJSON(ServiceResult.asFail("Please select file"));
        }
        String fileName = file.getName();
        int lastIndexOf = fileName.lastIndexOf(".");
        // 获取文件的后缀名 .jpg
        String suffix = fileName.substring(lastIndexOf);

        String key = System.nanoTime() + UUID.randomUUID().toString() + "." + suffix;
        String ossUrl = OssUtils.getClient().upload(key, file).obj;
        ServiceResult serviceResult = ServiceResult.asSuccess(ossUrl);
        renderJSON(serviceResult);
    }


    public static void saveVideoIndex(Long id, Long addSelectBigCateId, String urls, Integer sortOrder, String name, String banner) {
        if (StringUtils.isEmpty(urls)) {
            renderJSON(ServiceResult.asFail("请至少上传一个文件"));
        }
        VideoIndex videoIndex = new VideoIndex();
        if (id != null) {
            videoIndex = VideoIndex.findById(id);
        }
        videoIndex.banner = banner;
        videoIndex.bigCateId = addSelectBigCateId;
        videoIndex.name = name;
        videoIndex.sortOrder = sortOrder;
        videoIndex.urls = urls;
        videoIndex.save();
        renderJSON(ServiceResult.asSuccess("保存成功"));
    }

    public static void queryVideoIndex(Long bigCateId) {
        String sql = "isDelete = 0 ";
        if (bigCateId != null) {
            sql += " and bigCateId=" + bigCateId;
        }
        List<VideoIndex> videoIndex = VideoIndex.find(sql + " order by sortOrder desc").fetch(100);
        List<BigCate> bigCates = BigCate.findAll();
        Map<Long, BigCate> bigCateMap = bigCates.stream().collect(Collectors.toMap(e -> e.id, e -> e));
        videoIndex.forEach(e -> {
            if (e.bigCateId != null) {
                BigCate cate = bigCateMap.get(e.bigCateId);
                e.cateName = cate.name;
            }
        });
        renderJSON(ServiceQueryResult.asSuccess(videoIndex));
    }

    public static void delVideoIndex(Long id) {
        if (id == null) {
            renderJSON(ServiceResult.asFail("参数异常"));
        }
        VideoIndex.findById(id)._delete();
        renderJSON(ServiceResult.asSuccess("删除成功"));
    }


    public static void deleteBigCate(Long id) {
        BigCate bigCate = BigCate.findById(id);
        if (bigCate != null) {
            bigCate.isDelete = 1;
            bigCate.save();
        }
        renderJSON(ServiceResult.asSuccess("删除成功"));
    }


    public static void saveBigCate(Long id, String name, Integer sortOrder, List<String> bannerUrlsShow) {
        BigCate bigCate = null;
        if (id != null) {
            bigCate = BigCate.findById(id);
        } else {
            bigCate = new BigCate();
        }
        if (CollectionUtils.isNotEmpty(bannerUrlsShow)) {
            List<AppBanner> appBanners = Lists.newArrayList();
            bannerUrlsShow.forEach(e -> {
                AppBanner appBanner = JSONUtil.toBean(e, AppBanner.class);
                appBanners.add(appBanner);
            });
            bigCate.bannerUrls = GsonUtils.toJson(appBanners);
        }
        bigCate.name = name;
        bigCate.sortOrder = sortOrder;
        bigCate.save();
        renderJSON(ServiceResult.asSuccess("保存成功"));
    }


    public static void addOrEditKeJian(Long id, String title, String fileUrl, Integer vipSub, BigDecimal fee, Long selectBigCateId, Integer sortOrder,
                                       String banner, Long subCateId, String detailUrl) {
        if (StringUtils.isEmpty(title)) {
            renderJSON(ServiceResult.asFail("请输入标题"));
        }
        if (StringUtils.isEmpty(fileUrl)) {
            renderJSON(ServiceResult.asFail("请选择文件"));
        }
        if (subCateId == null) {
            renderJSON(ServiceResult.asFail("请选择子分类"));
        }
        if (selectBigCateId == null) {
            renderJSON(ServiceResult.asFail("请选择大类"));
        }
        if (sortOrder == null) {
            renderJSON(ServiceResult.asFail("请输入排序"));
        }
        if (StringUtils.isEmpty(banner)) {
            renderJSON(ServiceResult.asFail("请上传封面图"));
        }
        KeJian keJian;
        if (id != null) {
            keJian = KeJian.findById(id);
        } else {
            keJian = new KeJian();
        }
        keJian.gmtModify = new Date();
        keJian.selectBigCateId = selectBigCateId;
        keJian.fileUrl = fileUrl;
        keJian.subCateId = subCateId;
        keJian.banner = banner;
        keJian.sortOrder = sortOrder;
        keJian.title = title;
        keJian.detailUrl = detailUrl;
        keJian.vipSub = vipSub;
        keJian.fee = fee;
        keJian.save();
        renderJSON(ServiceResult.asSuccess("操作成功"));
    }

    public static void queryKeJian(Long selectBigCateId, Long cateId, int page, int limit) {
        ServiceQueryResult<KeJian> resData = KeJianService.queryData(selectBigCateId, cateId, page, limit);
        List<BigCate> bigCates = BigCate.findAll();
        Map<Long, BigCate> bigCateMap = bigCates.stream().collect(Collectors.toMap(e -> e.id, e -> e));
        resData.obj.forEach(e -> {
            if (e.selectBigCateId != null) {
                BigCate cate = bigCateMap.get(e.selectBigCateId);
                e.selectBigCateShow = cate.name;
            }
        });

        List<KeJianCategory> keJianCategories = KeJianCategory.findAll();
        Map<Long, KeJianCategory> keJianCategoryMap = keJianCategories.stream().collect(Collectors.toMap(e -> e.id, e -> e));
        resData.obj.forEach(e -> {
            if (e.subCateId != null) {
                KeJianCategory cate = keJianCategoryMap.get(e.subCateId);
                e.subCateShow = cate.name;
            }
        });

        renderJSON(resData.toJson(KeJian.class));
    }


    public static void deleteKeJian(Long keJianId) {
        if (keJianId == null) {
            renderJSON(ServiceResult.asFail("无效的参数"));
        }
        KeJian keJian = KeJian.findById(keJianId);
        keJian.isDelete = 1;
        keJian.save();
        renderJSON(ServiceResult.asSuccess("删除成功"));
    }


    public static void uploadTiKu(boolean isClear, Long childCateId, File file) {
        if (childCateId == null || file == null) {
            renderJSON(ServiceResult.asFail("上传失败，请检查"));
        }

        if (isClear) {
            List<QuestionAnswer> questionAnswers = QuestionAnswer.find("isDelete = 0 and childCateId=:childCateId").setParameter(
                    "childCateId", childCateId).fetch();
            for (QuestionAnswer questionAnswer : questionAnswers) {
                questionAnswer.isDelete = 1;
                questionAnswer.save();
            }
        }
        ChildSubjectDictionary dictionary = ChildSubjectDictionary.findById(childCateId);
        SubjectDictionary subjectDictionary = SubjectDictionary.findById(dictionary.parentId);
        BigCate bigCate = BigCate.findById(subjectDictionary.bigCateId);
        ExcelReader reader = ExcelUtil.getReader(file);
        assembleReader(reader);
        List<ImportExcelVo> importExcelVos = reader.readAll(ImportExcelVo.class);
        if (CollectionUtils.isEmpty(importExcelVos)) {
            renderJSON(ServiceResult.asSuccess("success"));
        }
        if(importExcelVos.size() > 150){
            renderJSON(ServiceResult.asFail("为了达到最佳效果，每一个子章节限制最多150个题目"));
        }
        int x = importExcelVos.size();
        for (ImportExcelVo e : importExcelVos) {
            QuestionAnswer questionAnswer = new QuestionAnswer();
            questionAnswer.question = e.question;
            questionAnswer.sortOrder = x--;
            questionAnswer.answerDesc = e.jiexi;
            questionAnswer.bigCateId = bigCate.id;
            questionAnswer.subCateId = subjectDictionary.id;
            questionAnswer.childCateId = childCateId;
            List<String> answers = Splitter.on("；").splitToList(e.answer.toLowerCase());
            List<String> abcd = Lists.newArrayList();
            if (StringUtils.isNotEmpty(e.a)) {
                AnswerDO answerDO = new AnswerDO();
                answerDO.answer = e.a;
                if (answers.contains("a")) {
                    answerDO.isAnswer = true;
                }
                abcd.add(answerDO.toJson());
            }
            if (StringUtils.isNotEmpty(e.b)) {
                AnswerDO answerDO = new AnswerDO();
                answerDO.answer = e.b;
                if (answers.contains("b")) {
                    answerDO.isAnswer = true;
                }
                abcd.add(answerDO.toJson());
            }
            if (StringUtils.isNotEmpty(e.c)) {
                AnswerDO answerDO = new AnswerDO();
                answerDO.answer = e.c;
                if (answers.contains("c")) {
                    answerDO.isAnswer = true;
                }
                abcd.add(answerDO.toJson());
            }
            if (StringUtils.isNotEmpty(e.d)) {
                AnswerDO answerDO = new AnswerDO();
                answerDO.answer = e.d;
                if (answers.contains("d")) {
                    answerDO.isAnswer = true;
                }
                abcd.add(answerDO.toJson());
            }
            if (StringUtils.isNotEmpty(e.e)) {
                AnswerDO answerDO = new AnswerDO();
                answerDO.answer = e.e;
                if (answers.contains("e")) {
                    answerDO.isAnswer = true;
                }
                abcd.add(answerDO.toJson());
            }
            if (StringUtils.isNotEmpty(e.f)) {
                AnswerDO answerDO = new AnswerDO();
                answerDO.answer = e.f;
                if (answers.contains("f")) {
                    answerDO.isAnswer = true;
                }
                abcd.add(answerDO.toJson());
            }
            if (StringUtils.isNotEmpty(e.g)) {
                AnswerDO answerDO = new AnswerDO();
                answerDO.answer = e.g;
                if (answers.contains("g")) {
                    answerDO.isAnswer = true;
                }
                abcd.add(answerDO.toJson());
            }
            questionAnswer.selectAbleData = JSONUtil.toJsonStr(abcd);
            questionAnswer.save();
        }
        renderJSON(ServiceResult.asSuccess("Success"));
    }


    private static void assembleReader(ExcelReader reader) {
        reader.addHeaderAlias("*题目", "question");
        reader.addHeaderAlias("*正确答案", "answer");
        reader.addHeaderAlias("*选项A", "a");
        reader.addHeaderAlias("*选项B", "b");
        reader.addHeaderAlias("选项C", "c");
        reader.addHeaderAlias("选项D", "d");
        reader.addHeaderAlias("选项E", "e");
        reader.addHeaderAlias("选项F", "f");
        reader.addHeaderAlias("选项G", "g");
        reader.addHeaderAlias("试题解析", "jiexi");
    }


    public static void addOrEditKeJianCategory(Long id, Integer sortOrder, String name, String banner, Long bigCateId, Integer vipSub,
                                               BigDecimal fee) {
        KeJianCategory keJianCategory = new KeJianCategory();
        if (id != null) {
            keJianCategory = KeJianCategory.findById(id);
        }

        keJianCategory.banner = banner;
        keJianCategory.name = name;
        keJianCategory.bigCateId = bigCateId;
        keJianCategory.vipSub = vipSub;
        keJianCategory.sortOrder = sortOrder;
        keJianCategory.fee = fee;
        keJianCategory.save();
        renderJSON(ServiceResult.asSuccess("保存成功"));
    }

    public static void deleteKeJianCate(Long cateId) {
        if (cateId == null) {
            renderJSON(ServiceResult.asFail("无效的参数"));
        }
        KeJianCategory keJian = KeJianCategory.findById(cateId);
        keJian.isDelete = 1;
        keJian.save();
        renderJSON(ServiceResult.asSuccess("删除成功"));
    }


    public static void queryKeJianCate(Long bigCateId) {
        String sql = "isDelete = 0 ";
        if (bigCateId != null) {
            sql += " and bigCateId=" + bigCateId;
        }
        List<KeJianCategory> keJianCategories = KeJianCategory.find(sql + " order by sortOrder desc").fetch();

        List<BigCate> bigCates = BigCate.findAll();
        Map<Long, BigCate> bigCateMap = bigCates.stream().collect(Collectors.toMap(e -> e.id, e -> e));
        keJianCategories.forEach(e -> {
            if (e.bigCateId != null) {
                BigCate cate = bigCateMap.get(e.bigCateId);
                e.selectBigCateShow = cate.name;
            }
        });
        renderJSON(ServiceQueryResult.asSuccess(keJianCategories).toJson(KeJianCategory.class));
    }
}
